package com.phf.vhr.service.impl;

import com.phf.vhr.mapper.UsersRolesMapper;
import com.phf.vhr.model.entity.RolesDO;
import com.phf.vhr.model.entity.SecurityUser;
import com.phf.vhr.model.entity.UsersDO;
import com.phf.vhr.mapper.UsersMapper;
import com.phf.vhr.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author phf
 * @since 2021-09-26
 */
@Service("userServiceImpl")
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersDO> implements UsersService,UserDetailsService{
    
    @Autowired
    UsersRolesMapper usersRolesMapper;

    /**
     * 执行用户登录
     * 
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        
        log.info("UsersServiceImpl [] 登录用户名： {}", userName);
        UsersDO oneUser = baseMapper.getOneUser(userName);
        if (oneUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }         
        //获取该用户拥有的角色
        List<RolesDO> userRolesLists = usersRolesMapper.getUserRolesStringByUserId(oneUser.getId());
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUserName(userName);
        securityUser.setPassword(oneUser.getPassword());
        securityUser.setRoles(userRolesLists);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, oneUser.getPassword(), securityUser.getAuthorities());
        return securityUser;
    }
}
